import storage from 'store'
import { login } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const user = {
  state: {
    token: '',
    userinfo: {}
  },

  mutations: {
    setToken: (state, token) => {
      state.token = token
    },
    setUserinfo: (state, userinfor) => {
      state.userinfo = userinfor
    }
  },

  actions: {
    // 登录
    login ({ commit }, userinfo) {
      return new Promise((resolve, reject) => {
        login(userinfo).then(response => {
          const result = response
          const token = result.token
          storage.set(ACCESS_TOKEN, token, 7 * 24 * 60 * 60 * 1000)
          commit('setToken', token)
          resolve(result.data)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
